import { DataTypes } from 'sequelize';
import { sequelize } from '../config/database.js';

const Domain = sequelize.define('Domain', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '领域名称'
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '领域描述'
  },
  welcome_message_1: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '欢迎语1'
  },
  welcome_message_2: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '欢迎语2'
  },
  precondition_config: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '前置条件配置JSON',
    get() {
      const value = this.getDataValue('precondition_config');
      return value ? (typeof value === 'string' ? JSON.parse(value) : value) : null;
    },
    set(value) {
      this.setDataValue('precondition_config', value ? JSON.stringify(value) : null);
    }
  },
  is_enabled: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    comment: '是否启用'
  },
  sort_order: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: '排序权重'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'domains',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_domains_is_enabled',
      fields: ['is_enabled'],
    },
    {
      name: 'idx_domains_sort_order',
      fields: ['sort_order'],
    },
  ],
});

// 实例方法
Domain.prototype.toJSON = function() {
  const values = { ...this.get() };
  return values;
};

// 类方法
Domain.getEnabledDomains = function() {
  return this.findAll({
    where: { is_enabled: true },
    order: [['sort_order', 'ASC'], ['created_at', 'ASC']]
  });
};

Domain.findByIdWithExperts = function(id) {
  return this.findByPk(id, {
    include: [{
      association: 'experts',
      where: { is_enabled: true },
      required: false,
      order: [['sort_order', 'ASC']]
    }]
  });
};

export default Domain;
